import type { KnowledgeDetail } from '@/types/knowledge';

/**
 * Java 8+ 新特性知识点数据
 */
export const java8Knowledge : KnowledgeDetail[] = [
	{
		id: 21,
		title: 'Lambda表达式',
		description: 'Java 8核心特性，函数式编程，简化代码编写，提高可读性，是现代Java开发必备。',
		icon: '⚡',
		categoryId: 'java8',
		categoryName: 'Java 8+ 新特性',
		categoryIcon: '⚡',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'Lambda表达式语法：(参数列表) -> {表达式或语句块}，简化匿名内部类的写法。',
				code: `import java.util.*;

public class LambdaSyntax {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Java", "Python", "C++");
        
        // 无参数Lambda
        Runnable r = () -> System.out.println("Hello Lambda");
        r.run();
        
        // 单参数Lambda（可省略括号）
        list.forEach(s -> System.out.println(s));
        
        // 多参数Lambda
        Comparator<String> comparator = (s1, s2) -> s1.length() - s2.length();
        list.sort(comparator);
        
        // 多行Lambda（需要花括号）
        list.forEach(s -> {
            String upper = s.toUpperCase();
            System.out.println("语言: " + upper);
        });
        
        // 带返回值的Lambda
        Calculator add = (a, b) -> a + b;
        System.out.println(add.calculate(5, 3));  // 8
    }
    
    @FunctionalInterface
    interface Calculator {
        int calculate(int a, int b);
    }
}`
			},
			{
				point: '函数式接口使用@FunctionalInterface标注，只能有一个抽象方法，是Lambda表达式的基础。',
				code: `import java.util.function.*;

// 自定义函数式接口
@FunctionalInterface
public interface MyFunction<T, R> {
    R apply(T t);  // 唯一抽象方法
    
    // 可以有默认方法
    default void printInfo() {
        System.out.println("Function interface");
    }
    
    // 可以有静态方法
    static void staticMethod() {
        System.out.println("Static method");
    }
}

// 使用示例
public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        // 自定义函数式接口
        MyFunction<String, Integer> getLength = s -> s.length();
        System.out.println(getLength.apply("Hello"));  // 5
        
        // Java内置函数式接口
        // Function<T, R>: 接受T返回R
        Function<String, Integer> toLength = String::length;
        
        // Consumer<T>: 接受T无返回
        Consumer<String> printer = System.out::println;
        
        // Supplier<T>: 无参数返回T
        Supplier<Double> random = Math::random;
        
        // Predicate<T>: 接受T返回boolean
        Predicate<Integer> isEven = n -> n % 2 == 0;
        
        // BiFunction<T, U, R>: 接受T和U返回R
        BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
    }
}`
			},
			{
				point: '方法引用使用::语法，是Lambda表达式的简化形式，包括静态方法、实例方法、构造方法引用。',
				code: `import java.util.*;
import java.util.function.*;

public class MethodReferenceDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("apple", "banana", "cherry");
        
        // 1. 静态方法引用 ClassName::staticMethod
        // Lambda: s -> Integer.parseInt(s)
        Function<String, Integer> parser = Integer::parseInt;
        Integer num = parser.apply("123");
        
        // 2. 特定对象的实例方法引用 object::instanceMethod
        String prefix = "Hello ";
        // Lambda: s -> prefix.concat(s)
        Function<String, String> greeter = prefix::concat;
        System.out.println(greeter.apply("World"));
        
        // 3. 特定类型的任意对象的实例方法引用 ClassName::instanceMethod
        // Lambda: s -> s.toUpperCase()
        list.stream()
            .map(String::toUpperCase)
            .forEach(System.out::println);
        
        // 4. 构造方法引用 ClassName::new
        // Lambda: () -> new ArrayList<>()
        Supplier<List<String>> listSupplier = ArrayList::new;
        List<String> newList = listSupplier.get();
        
        // 数组构造方法引用
        Function<Integer, String[]> arrayCreator = String[]::new;
        String[] array = arrayCreator.apply(5);
    }
}`
			},
			{
				point: 'Java内置函数式接口：Function、Consumer、Supplier、Predicate等，涵盖常见的函数操作场景。',
				code: `import java.util.*;
import java.util.function.*;

public class FunctionalInterfacesDemo {
    public static void main(String[] args) {
        // Predicate<T>: T -> boolean（条件判断）
        Predicate<Integer> isPositive = n -> n > 0;
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Predicate<Integer> isPositiveEven = isPositive.and(isEven);
        System.out.println(isPositiveEven.test(4));  // true
        
        // Function<T, R>: T -> R（类型转换）
        Function<String, Integer> strLength = String::length;
        Function<Integer, String> intToStr = Object::toString;
        Function<String, String> combined = strLength.andThen(intToStr);
        
        // Consumer<T>: T -> void（消费数据）
        Consumer<String> printer = System.out::println;
        Consumer<String> upperPrinter = s -> System.out.println(s.toUpperCase());
        Consumer<String> combined2 = printer.andThen(upperPrinter);
        combined2.accept("hello");
        
        // Supplier<T>: () -> T（提供数据）
        Supplier<UUID> uuidSupplier = UUID::randomUUID;
        System.out.println(uuidSupplier.get());
        
        // BiFunction<T, U, R>: (T, U) -> R（双参数函数）
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
        System.out.println(add.apply(5, 3));
        
        // UnaryOperator<T>: T -> T（一元操作）
        UnaryOperator<String> toUpper = String::toUpperCase;
        
        // BinaryOperator<T>: (T, T) -> T（二元操作）
        BinaryOperator<Integer> max = Integer::max;
    }
}`
			},
			{
				point: 'Lambda表达式可以访问外部变量，但变量必须是final或等效final（实际上不可变）。',
				code: `import java.util.*;

public class LambdaVariableCapture {
    private int instanceVar = 100;
    private static int staticVar = 200;
    
    public void demonstrateCapture() {
        final int finalVar = 10;
        int effectiveFinalVar = 20;
        
        // ✅ 可以访问final变量
        Runnable r1 = () -> {
            System.out.println("Final: " + finalVar);
        };
        
        // ✅ 可以访问等效final变量
        Runnable r2 = () -> {
            System.out.println("Effective final: " + effectiveFinalVar);
        };
        
        // ✅ 可以访问实例变量和静态变量
        Runnable r3 = () -> {
            System.out.println("Instance: " + instanceVar);
            System.out.println("Static: " + staticVar);
        };
        
        // ❌ 不能访问非final的局部变量
        int mutableVar = 30;
        // Runnable r4 = () -> System.out.println(mutableVar);
        // mutableVar = 40;  // 这会导致上面的Lambda编译错误
        
        // ✅ 可以修改实例变量
        Runnable r5 = () -> {
            this.instanceVar = 999;  // OK
        };
        
        r1.run();
        r2.run();
        r3.run();
        r5.run();
    }
    
    public static void main(String[] args) {
        new LambdaVariableCapture().demonstrateCapture();
    }
}`
			}
		]
	},
	{
		id: 22,
		title: 'Stream API',
		description: 'Java 8流式处理，函数式操作集合，filter、map、reduce等操作，让集合处理更优雅。',
		icon: '🌊',
		categoryId: 'java8',
		categoryName: 'Java 8+ 新特性',
		categoryIcon: '⚡',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #fdcbf1 0%, #e6dee9 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'Stream创建有多种方式：集合.stream()、Stream.of()、Stream.generate()、Stream.iterate()等。',
				code: `import java.util.*;
import java.util.stream.*;

public class StreamCreation {
    public static void main(String[] args) {
        // 1. 从集合创建
        List<String> list = Arrays.asList("a", "b", "c");
        Stream<String> stream1 = list.stream();
        
        // 2. 从数组创建
        String[] array = {"d", "e", "f"};
        Stream<String> stream2 = Arrays.stream(array);
        
        // 3. 使用Stream.of()
        Stream<String> stream3 = Stream.of("g", "h", "i");
        
        // 4. 无限流 - generate
        Stream<Double> randomStream = Stream.generate(Math::random)
            .limit(5);  // 限制5个
        
        // 5. 无限流 - iterate
        Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2)
            .limit(10);  // 0, 2, 4, 6, ...
        
        // 6. 空Stream
        Stream<String> emptyStream = Stream.empty();
        
        // 7. 并行流
        Stream<String> parallelStream = list.parallelStream();
        
        // 8. 范围数值流
        IntStream range = IntStream.range(1, 10);  // 1-9
        LongStream rangeClosed = LongStream.rangeClosed(1, 10);  // 1-10
    }
}`
			},
			{
				point: '中间操作（惰性求值）：filter过滤、map转换、sorted排序、distinct去重、limit限制、skip跳过等。',
				code: `import java.util.*;
import java.util.stream.*;

public class StreamIntermediateOps {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        
        // filter: 过滤元素
        List<Integer> evens = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());  // [2, 4, 6, 8, 10]
        
        // map: 转换元素
        List<Integer> doubled = numbers.stream()
            .map(n -> n * 2)
            .collect(Collectors.toList());
        
        // flatMap: 扁平化
        List<List<Integer>> nested = Arrays.asList(
            Arrays.asList(1, 2),
            Arrays.asList(3, 4)
        );
        List<Integer> flattened = nested.stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toList());  // [1, 2, 3, 4]
        
        // distinct: 去重
        List<Integer> unique = Arrays.asList(1, 2, 2, 3, 3, 3).stream()
            .distinct()
            .collect(Collectors.toList());  // [1, 2, 3]
        
        // sorted: 排序
        List<Integer> sorted = numbers.stream()
            .sorted(Comparator.reverseOrder())
            .collect(Collectors.toList());
        
        // limit & skip: 限制和跳过
        List<Integer> limited = numbers.stream()
            .skip(3)    // 跳过前3个
            .limit(4)   // 取4个
            .collect(Collectors.toList());  // [4, 5, 6, 7]
        
        // peek: 调试查看（中间操作）
        numbers.stream()
            .peek(n -> System.out.println("Before: " + n))
            .map(n -> n * 2)
            .peek(n -> System.out.println("After: " + n))
            .collect(Collectors.toList());
    }
}`
			},
			{
				point: '终端操作（立即执行）：forEach遍历、collect收集、reduce聚合、count计数、anyMatch/allMatch/noneMatch匹配等。',
				code: `import java.util.*;
import java.util.stream.*;

public class StreamTerminalOps {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        // forEach: 遍历
        numbers.stream().forEach(System.out::println);
        
        // collect: 收集到集合
        List<Integer> list = numbers.stream().collect(Collectors.toList());
        Set<Integer> set = numbers.stream().collect(Collectors.toSet());
        
        // reduce: 聚合
        int sum = numbers.stream().reduce(0, (a, b) -> a + b);
        int sum2 = numbers.stream().reduce(0, Integer::sum);
        Optional<Integer> max = numbers.stream().reduce(Integer::max);
        
        // count: 计数
        long count = numbers.stream().filter(n -> n > 2).count();
        
        // min & max: 最小最大值
        Optional<Integer> min = numbers.stream().min(Integer::compareTo);
        Optional<Integer> max2 = numbers.stream().max(Integer::compareTo);
        
        // anyMatch, allMatch, noneMatch: 匹配
        boolean anyEven = numbers.stream().anyMatch(n -> n % 2 == 0);
        boolean allPositive = numbers.stream().allMatch(n -> n > 0);
        boolean noneNegative = numbers.stream().noneMatch(n -> n < 0);
        
        // findFirst & findAny: 查找
        Optional<Integer> first = numbers.stream().findFirst();
        Optional<Integer> any = numbers.stream().findAny();
        
        // toArray: 转数组
        Integer[] array = numbers.stream().toArray(Integer[]::new);
    }
}`
			},
			{
				point: 'Collectors工具类提供丰富的收集器：toList、toSet、toMap、joining、groupingBy、partitioningBy等。',
				code: `import java.util.*;
import java.util.stream.*;

public class CollectorsDemo {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
        
        // toList, toSet, toCollection
        List<String> list = words.stream().collect(Collectors.toList());
        Set<String> set = words.stream().collect(Collectors.toSet());
        TreeSet<String> treeSet = words.stream()
            .collect(Collectors.toCollection(TreeSet::new));
        
        // toMap
        Map<String, Integer> wordLengths = words.stream()
            .collect(Collectors.toMap(
                w -> w,              // key
                String::length       // value
            ));
        
        // joining: 字符串拼接
        String joined = words.stream().collect(Collectors.joining(", "));
        // "apple, banana, cherry, date"
        
        // groupingBy: 分组
        Map<Integer, List<String>> byLength = words.stream()
            .collect(Collectors.groupingBy(String::length));
        // {5=[apple], 6=[banana, cherry], 4=[date]}
        
        // partitioningBy: 分区（true/false）
        Map<Boolean, List<String>> partition = words.stream()
            .collect(Collectors.partitioningBy(w -> w.length() > 5));
        
        // counting, summingInt, averagingInt
        Long count = words.stream().collect(Collectors.counting());
        Integer totalLength = words.stream()
            .collect(Collectors.summingInt(String::length));
        Double avgLength = words.stream()
            .collect(Collectors.averagingInt(String::length));
        
        // 高级分组
        Map<Integer, Long> lengthCount = words.stream()
            .collect(Collectors.groupingBy(
                String::length,
                Collectors.counting()
            ));
    }
}`
			},
			{
				point: '并行流parallelStream()利用多核CPU提高性能，但需注意线程安全和顺序问题。',
				code: `import java.util.*;
import java.util.stream.*;

public class ParallelStreamDemo {
    public static void main(String[] args) {
        List<Integer> numbers = IntStream.rangeClosed(1, 1000000)
            .boxed()
            .collect(Collectors.toList());
        
        // 顺序流
        long start = System.currentTimeMillis();
        long sum1 = numbers.stream()
            .mapToLong(Integer::longValue)
            .sum();
        long sequential = System.currentTimeMillis() - start;
        System.out.println("顺序流耗时: " + sequential + "ms");
        
        // 并行流
        start = System.currentTimeMillis();
        long sum2 = numbers.parallelStream()
            .mapToLong(Integer::longValue)
            .sum();
        long parallel = System.currentTimeMillis() - start;
        System.out.println("并行流耗时: " + parallel + "ms");
        
        // 转换为并行流
        Stream<Integer> stream = numbers.stream();
        Stream<Integer> parallelStream = stream.parallel();
        
        // ⚠️ 注意线程安全问题
        List<Integer> results = new ArrayList<>();  // 非线程安全
        // ❌ 不推荐
        numbers.parallelStream().forEach(results::add);  // 可能出错
        
        // ✅ 推荐使用collect
        List<Integer> safeResults = numbers.parallelStream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        
        // 检查是否并行
        boolean isParallel = numbers.parallelStream().isParallel();
        
        // 转为顺序流
        Stream<Integer> sequentialStream = parallelStream.sequential();
    }
}`
			}
		]
	},
	{
		id: 23,
		title: 'Optional类',
		description: '优雅处理空指针异常，避免NullPointerException，提高代码的健壮性和可读性。',
		icon: '🎁',
		categoryId: 'java8',
		categoryName: 'Java 8+ 新特性',
		categoryIcon: '⚡',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'Optional创建：of()不接受null会抛异常，ofNullable()可接受null，empty()创建空Optional。',
				code: `import java.util.Optional;

public class OptionalCreation {
    public static void main(String[] args) {
        // 1. Optional.of() - 值不能为null
        Optional<String> opt1 = Optional.of("Hello");
        // Optional<String> opt2 = Optional.of(null);  // NullPointerException
        
        // 2. Optional.ofNullable() - 值可以为null
        Optional<String> opt3 = Optional.ofNullable("World");
        Optional<String> opt4 = Optional.ofNullable(null);  // OK，创建空Optional
        
        // 3. Optional.empty() - 创建空Optional
        Optional<String> opt5 = Optional.empty();
        
        // 判断是否有值
        System.out.println(opt1.isPresent());  // true
        System.out.println(opt4.isPresent());  // false
        System.out.println(opt5.isEmpty());    // true (Java 11+)
        
        // 实际场景：从Map获取值
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        
        // 传统方式
        String value1 = map.get("key2");
        if (value1 != null) {
            System.out.println(value1);
        }
        
        // Optional方式
        Optional.ofNullable(map.get("key2"))
            .ifPresent(System.out::println);
    }
}`
			},
			{
				point: 'isPresent()和ifPresent()方法：前者返回boolean，后者接受Consumer函数式接口。',
				code: `import java.util.Optional;

public class OptionalPresent {
    public static void main(String[] args) {
        Optional<String> optional = Optional.of("Hello");
        Optional<String> empty = Optional.empty();
        
        // isPresent(): 判断是否有值（返回boolean）
        if (optional.isPresent()) {
            String value = optional.get();
            System.out.println(value);
        }
        
        // ifPresent(): 如果有值则执行Consumer
        optional.ifPresent(value -> {
            System.out.println("值为: " + value);
        });
        
        // ifPresent()方法引用简化
        optional.ifPresent(System.out::println);
        
        // ifPresentOrElse() (Java 9+)
        optional.ifPresentOrElse(
            value -> System.out.println("有值: " + value),
            () -> System.out.println("没有值")
        );
        
        // ❌ 不推荐的用法
        if (optional.isPresent()) {
            System.out.println(optional.get());  // 不如直接用ifPresent
        }
        
        // ✅ 推荐的用法
        optional.ifPresent(System.out::println);
    }
    
    // 实际应用：查找用户
    public void findUser(Long userId) {
        Optional<User> userOpt = getUserById(userId);
        
        // 如果找到用户，打印信息
        userOpt.ifPresent(user -> {
            System.out.println("用户名: " + user.getName());
            System.out.println("邮箱: " + user.getEmail());
        });
    }
}`
			},
			{
				point: 'orElse()立即执行返回默认值，orElseGet()懒加载（Supplier），orElseThrow()抛出异常。',
				code: `import java.util.Optional;

public class OptionalOrElse {
    public static void main(String[] args) {
        Optional<String> optional = Optional.ofNullable(null);
        
        // orElse(): 立即执行，返回默认值
        String value1 = optional.orElse(getDefaultValue());
        // getDefaultValue()总会被调用
        
        // orElseGet(): 懒加载，只在空时调用Supplier
        String value2 = optional.orElseGet(() -> getDefaultValue());
        // 只有optional为空时才调用getDefaultValue()
        
        // orElseThrow(): 抛出异常
        try {
            String value3 = optional.orElseThrow(
                () -> new IllegalArgumentException("值不存在")
            );
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
        
        // orElseThrow() 无参版本 (Java 10+)
        // String value4 = optional.orElseThrow();  // NoSuchElementException
        
        // 性能对比
        Optional<String> opt = Optional.of("exist");
        
        // orElse：即使有值，也会调用方法
        String v1 = opt.orElse(expensiveOperation());
        
        // orElseGet：有值时不调用方法
        String v2 = opt.orElseGet(() -> expensiveOperation());
    }
    
    private static String getDefaultValue() {
        System.out.println("获取默认值");
        return "Default";
    }
    
    private static String expensiveOperation() {
        System.out.println("执行昂贵操作");
        return "Expensive";
    }
}`
			},
			{
				point: 'map()转换值，flatMap()转换为Optional并扁平化，filter()过滤值。',
				code: `import java.util.Optional;

public class OptionalTransform {
    public static void main(String[] args) {
        Optional<String> optional = Optional.of("Hello");
        
        // map(): 转换Optional中的值
        Optional<Integer> length = optional.map(String::length);
        System.out.println(length.get());  // 5
        
        Optional<String> upper = optional.map(String::toUpperCase);
        System.out.println(upper.get());  // HELLO
        
        // 链式map调用
        Optional<Character> firstChar = optional
            .map(String::toUpperCase)
            .map(s -> s.charAt(0));
        
        // filter(): 过滤值
        Optional<String> filtered = optional
            .filter(s -> s.length() > 3);
        System.out.println(filtered.isPresent());  // true
        
        // flatMap(): 避免Optional<Optional<T>>
        Optional<String> input = Optional.of("user123");
        
        // 使用map会产生Optional<Optional<User>>
        // Optional<Optional<User>> nested = input.map(this::findUser);
        
        // 使用flatMap扁平化
        Optional<User> user = input.flatMap(this::findUser);
        
        // 实际应用：安全的链式调用
        String cityName = getUserById(1L)
            .flatMap(User::getAddress)
            .flatMap(Address::getCity)
            .map(City::getName)
            .orElse("未知城市");
    }
    
    private Optional<User> findUser(String id) {
        // 模拟数据库查询
        return Optional.of(new User(id, "张三"));
    }
    
    private Optional<User> getUserById(Long id) {
        return Optional.of(new User("1", "李四"));
    }
    
    static class User {
        String id, name;
        User(String id, String name) {
            this.id = id;
            this.name = name;
        }
        Optional<Address> getAddress() {
            return Optional.of(new Address());
        }
    }
    
    static class Address {
        Optional<City> getCity() {
            return Optional.of(new City("北京"));
        }
    }
    
    static class City {
        String name;
        City(String name) { this.name = name; }
        String getName() { return name; }
    }
}`
			},
			{
				point: 'Optional最佳实践：不要用于字段、参数，避免直接get()，优先使用orElse/map/flatMap等方法。',
				code: `import java.util.Optional;

public class OptionalBestPractices {
    // ❌ 不推荐：Optional作为字段
    private Optional<String> name;
    
    // ✅ 推荐：直接使用可能为null的字段
    private String name2;
    
    // ❌ 不推荐：Optional作为参数
    public void processUser(Optional<User> user) {
        user.ifPresent(u -> System.out.println(u.getName()));
    }
    
    // ✅ 推荐：参数可以为null
    public void processUser2(User user) {
        if (user != null) {
            System.out.println(user.getName());
        }
    }
    
    // ✅ 推荐：Optional作为返回值
    public Optional<User> findUser(Long id) {
        User user = database.find(id);
        return Optional.ofNullable(user);
    }
    
    // ❌ 不推荐：直接使用get()
    public void badPractice() {
        Optional<String> opt = Optional.ofNullable(getValue());
        if (opt.isPresent()) {
            String value = opt.get();  // 不如直接用orElse
            System.out.println(value);
        }
    }
    
    // ✅ 推荐：使用orElse/map等方法
    public void goodPractice() {
        String value = Optional.ofNullable(getValue())
            .map(String::toUpperCase)
            .filter(s -> s.length() > 3)
            .orElse("DEFAULT");
        System.out.println(value);
    }
    
    // ✅ 推荐：集合操作
    public List<String> getActiveUserNames() {
        return getUsers().stream()
            .map(User::getName)  // 返回Optional<String>
            .flatMap(Optional::stream)  // Java 9+ 扁平化
            .collect(Collectors.toList());
    }
    
    // ❌ 不推荐：Optional嵌套
    Optional<Optional<String>> nested = Optional.of(Optional.of("Bad"));
    
    // ✅ 推荐：使用flatMap
    Optional<String> flattened = Optional.of("Good")
        .flatMap(s -> Optional.of(s.toUpperCase()));
}`
			}
		]
	},
	{
		id: 24,
		title: '新日期时间API',
		description: 'Java 8引入全新的日期时间API，解决旧Date类的问题，提供不可变、线程安全的日期时间处理。',
		icon: '📅',
		categoryId: 'java8',
		categoryName: 'Java 8+ 新特性',
		categoryIcon: '⚡',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #d299c2 0%, #fef9d7 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'LocalDate表示日期（年月日），LocalTime表示时间（时分秒），LocalDateTime表示日期时间。',
				code: `import java.time.*;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        // LocalDate：只有日期
        LocalDate today = LocalDate.now();
        LocalDate birthday = LocalDate.of(1990, 5, 15);
        LocalDate parsed = LocalDate.parse("2023-12-25");
        
        System.out.println("今天: " + today);
        System.out.println("年: " + today.getYear());
        System.out.println("月: " + today.getMonthValue());
        System.out.println("日: " + today.getDayOfMonth());
        System.out.println("星期: " + today.getDayOfWeek());
        
        // LocalTime：只有时间
        LocalTime now = LocalTime.now();
        LocalTime time = LocalTime.of(14, 30, 0);
        
        System.out.println("当前时间: " + now);
        System.out.println("时: " + now.getHour());
        System.out.println("分: " + now.getMinute());
        
        // LocalDateTime：日期+时间
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime specific = LocalDateTime.of(2023, 12, 25, 14, 30);
        
        // 组合LocalDate和LocalTime
        LocalDateTime combined = LocalDate.now().atTime(LocalTime.now());
    }
}`
			},
			{
				point: '日期时间计算：plus/minus系列方法，with方法设置字段，Period和Duration计算间隔。',
				code: `import java.time.*;
import java.time.temporal.ChronoUnit;

public class DateCalculation {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        
        // plus系列：增加时间
        LocalDate tomorrow = today.plusDays(1);
        LocalDate nextWeek = today.plusWeeks(1);
        LocalDate nextMonth = today.plusMonths(1);
        LocalDate nextYear = today.plusYears(1);
        
        // minus系列：减少时间
        LocalDate yesterday = today.minusDays(1);
        LocalDate lastMonth = today.minusMonths(1);
        
        // with系列：设置字段
        LocalDate firstDay = today.withDayOfMonth(1);
        LocalDate newYear = today.withMonth(1).withDayOfMonth(1);
        
        // Period：日期间隔（年月日）
        LocalDate birth = LocalDate.of(1990, 5, 15);
        Period age = Period.between(birth, today);
        System.out.println("年龄: " + age.getYears() + "岁" 
            + age.getMonths() + "月" + age.getDays() + "天");
        
        // Duration：时间间隔（时分秒）
        LocalTime start = LocalTime.of(9, 0);
        LocalTime end = LocalTime.of(17, 30);
        Duration workTime = Duration.between(start, end);
        System.out.println("工作时长: " + workTime.toHours() + "小时");
        
        // ChronoUnit：计算时间差
        long days = ChronoUnit.DAYS.between(birth, today);
        long months = ChronoUnit.MONTHS.between(birth, today);
        System.out.println("已过" + days + "天，" + months + "月");
    }
}`
			},
			{
				point: 'DateTimeFormatter格式化和解析日期时间，支持自定义格式和本地化。',
				code: `import java.time.*;
import java.time.format.*;
import java.util.Locale;

public class DateTimeFormatterDemo {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        
        // 预定义格式
        String iso = now.format(DateTimeFormatter.ISO_DATE_TIME);
        String basic = now.format(DateTimeFormatter.BASIC_ISO_DATE);
        
        // 自定义格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted1 = now.format(formatter1);
        System.out.println(formatted1);  // 2023-12-25 14:30:00
        
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分");
        String formatted2 = now.format(formatter2);
        System.out.println(formatted2);  // 2023年12月25日 14时30分
        
        // 本地化格式
        DateTimeFormatter usFormatter = DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.FULL)
            .withLocale(Locale.US);
        String usFormat = now.format(usFormatter);
        
        DateTimeFormatter cnFormatter = DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.FULL)
            .withLocale(Locale.CHINA);
        String cnFormat = now.format(cnFormatter);
        
        // 解析字符串
        String dateStr = "2023-12-25 14:30:00";
        LocalDateTime parsed = LocalDateTime.parse(dateStr, formatter1);
        
        // 解析日期
        String dateStr2 = "2023-12-25";
        LocalDate date = LocalDate.parse(dateStr2);
    }
}`
			},
			{
				point: 'ZonedDateTime处理时区，Instant表示时间戳，适用于记录事件发生时间。',
				code: `import java.time.*;

public class ZonedDateTimeDemo {
    public static void main(String[] args) {
        // 当前时区的日期时间
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println("当前: " + now);
        
        // 指定时区
        ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
        ZonedDateTime ny = ZonedDateTime.now(ZoneId.of("America/New_York"));
        
        System.out.println("东京: " + tokyo);
        System.out.println("纽约: " + ny);
        
        // 时区转换
        ZonedDateTime tokyoTime = now.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
        
        // 获取所有时区ID
        Set<String> zones = ZoneId.getAvailableZoneIds();
        
        // Instant：时间戳（UTC时区）
        Instant instant = Instant.now();
        long epochSecond = instant.getEpochSecond();  // 秒
        long epochMilli = instant.toEpochMilli();     // 毫秒
        
        System.out.println("时间戳: " + instant);
        System.out.println("秒: " + epochSecond);
        System.out.println("毫秒: " + epochMilli);
        
        // Instant与其他类型转换
        Instant fromEpoch = Instant.ofEpochMilli(System.currentTimeMillis());
        ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
        LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}`
			},
			{
				point: '新旧API转换：Date与Instant互转，Calendar与LocalDateTime互转。',
				code: `import java.time.*;
import java.util.Date;
import java.util.Calendar;

public class DateConversion {
    public static void main(String[] args) {
        // ========== Date <-> Instant ==========
        // Date转Instant
        Date oldDate = new Date();
        Instant instant = oldDate.toInstant();
        
        // Instant转Date
        Date newDate = Date.from(instant);
        
        // ========== Date <-> LocalDateTime ==========
        // Date转LocalDateTime
        Date date = new Date();
        LocalDateTime ldt = LocalDateTime.ofInstant(
            date.toInstant(), 
            ZoneId.systemDefault()
        );
        
        // LocalDateTime转Date
        LocalDateTime localDateTime = LocalDateTime.now();
        Date dateFromLdt = Date.from(
            localDateTime.atZone(ZoneId.systemDefault()).toInstant()
        );
        
        // ========== Calendar <-> LocalDateTime ==========
        // Calendar转LocalDateTime
        Calendar calendar = Calendar.getInstance();
        LocalDateTime ldtFromCal = LocalDateTime.ofInstant(
            calendar.toInstant(),
            calendar.getTimeZone().toZoneId()
        );
        
        // LocalDateTime转Calendar
        LocalDateTime now = LocalDateTime.now();
        Calendar calFromLdt = Calendar.getInstance();
        calFromLdt.setTime(Date.from(
            now.atZone(ZoneId.systemDefault()).toInstant()
        ));
        
        // ========== 时间戳转换 ==========
        // long时间戳 -> LocalDateTime
        long timestamp = System.currentTimeMillis();
        LocalDateTime ldtFromTs = LocalDateTime.ofInstant(
            Instant.ofEpochMilli(timestamp),
            ZoneId.systemDefault()
        );
        
        // LocalDateTime -> long时间戳
        long tsFromLdt = LocalDateTime.now()
            .atZone(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();
    }
}`
			}
		]
	},
	{
		id: 25,
		title: '接口默认方法',
		description: 'Java 8允许接口定义默认方法和静态方法，提高接口的扩展性，解决接口演化问题。',
		icon: '🔌',
		categoryId: 'java8',
		categoryName: 'Java 8+ 新特性',
		categoryIcon: '⚡',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '使用default关键字定义默认方法，实现类可以选择使用或重写默认方法。',
				code: `// 定义接口默认方法
public interface Vehicle {
    // 抽象方法
    void start();
    void stop();
    
    // 默认方法
    default void honk() {
        System.out.println("Beep beep!");
    }
    
    default void displayInfo() {
        System.out.println("This is a vehicle");
    }
}

// 实现类1：使用默认方法
public class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car starting");
    }
    
    @Override
    public void stop() {
        System.out.println("Car stopping");
    }
    
    // 使用默认的honk()方法
}

// 实现类2：重写默认方法
public class Truck implements Vehicle {
    @Override
    public void start() {
        System.out.println("Truck starting");
    }
    
    @Override
    public void stop() {
        System.out.println("Truck stopping");
    }
    
    // 重写默认方法
    @Override
    public void honk() {
        System.out.println("HONK HONK!");  // 卡车的喇叭声更大
    }
}

// 使用
Car car = new Car();
car.honk();  // Beep beep!

Truck truck = new Truck();
truck.honk();  // HONK HONK!`
			},
			{
				point: '接口中的静态方法使用static关键字，只能通过接口名调用，不能被实现类继承。',
				code: `public interface MathUtils {
    // 抽象方法
    int calculate(int a, int b);
    
    // 默认方法
    default void printResult(int result) {
        System.out.println("Result: " + result);
    }
    
    // 静态方法
    static int add(int a, int b) {
        return a + b;
    }
    
    static int multiply(int a, int b) {
        return a * b;
    }
    
    static boolean isPositive(int number) {
        return number > 0;
    }
}

public class Calculator implements MathUtils {
    @Override
    public int calculate(int a, int b) {
        // 只能通过接口名调用静态方法
        int sum = MathUtils.add(a, b);
        return sum;
    }
    
    public static void main(String[] args) {
        // 通过接口名调用静态方法
        int result = MathUtils.add(5, 3);
        System.out.println(result);  // 8
        
        // ❌ 不能通过实现类调用
        // int result2 = Calculator.add(5, 3);  // 编译错误
        
        Calculator calc = new Calculator();
        // ❌ 不能通过实例调用
        // int result3 = calc.add(5, 3);  // 编译错误
    }
}`
			},
			{
				point: '默认方法的多继承冲突：实现类优先、子接口优先、显式选择。',
				code: `// 接口1
public interface Interface1 {
    default void hello() {
        System.out.println("Hello from Interface1");
    }
}

// 接口2
public interface Interface2 {
    default void hello() {
        System.out.println("Hello from Interface2");
    }
}

// 规则1：实现类优先
class Parent {
    public void hello() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent implements Interface1 {
    // 使用Parent的hello()，而不是Interface1的
}

// 规则2：子接口优先
interface SubInterface extends Interface1 {
    @Override
    default void hello() {
        System.out.println("Hello from SubInterface");
    }
}

class Implementation implements SubInterface, Interface1 {
    // 使用SubInterface的hello()
}

// 规则3：显式选择（解决冲突）
class MultiImpl implements Interface1, Interface2 {
    @Override
    public void hello() {
        // 必须重写，否则编译错误
        // 可以选择调用某个接口的默认方法
        Interface1.super.hello();
        Interface2.super.hello();
        // 或提供自己的实现
        System.out.println("Hello from MultiImpl");
    }
}

public class Test {
    public static void main(String[] args) {
        new Child().hello();  // Hello from Parent
        new Implementation().hello();  // Hello from SubInterface
        new MultiImpl().hello();  // 自定义实现
    }
}`
			},
			{
				point: '默认方法的作用：保持二进制兼容性，为接口添加新方法而不破坏现有实现。',
				code: `// Java 8之前的Collection接口（简化版）
public interface CollectionBefore {
    boolean add(Object o);
    boolean remove(Object o);
    int size();
    // ... 其他方法
}

// 假设有很多实现类
public class MyListBefore implements CollectionBefore {
    @Override
    public boolean add(Object o) { return true; }
    @Override
    public boolean remove(Object o) { return true; }
    @Override
    public int size() { return 0; }
}

// Java 8要添加forEach和stream方法
// 如果不使用默认方法，所有实现类都要修改
public interface CollectionAfter {
    boolean add(Object o);
    boolean remove(Object o);
    int size();
    
    // ✅ 使用默认方法，不破坏现有实现
    default void forEach(Consumer<?> action) {
        for (Object item : this) {
            action.accept(item);
        }
    }
    
    default Stream<?> stream() {
        return StreamSupport.stream(spliterator(), false);
    }
}

// 现有实现类无需修改即可使用新方法
public class MyListAfter implements CollectionAfter {
    @Override
    public boolean add(Object o) { return true; }
    @Override
    public boolean remove(Object o) { return true; }
    @Override
    public int size() { return 0; }
    
    // 自动继承了forEach和stream方法
}

// 使用
MyListAfter list = new MyListAfter();
list.forEach(System.out::println);  // 可以直接使用！`
			},
			{
				point: 'Java 9+接口支持私有方法和私有静态方法，用于在接口内部复用代码。',
				code: `public interface ModernInterface {
    // 抽象方法
    void publicMethod();
    
    // 默认方法
    default void defaultMethod1() {
        System.out.println("Method 1");
        commonLogic();  // 调用私有方法
    }
    
    default void defaultMethod2() {
        System.out.println("Method 2");
        commonLogic();  // 复用私有方法
    }
    
    // 私有方法（Java 9+）- 只能在接口内部使用
    private void commonLogic() {
        System.out.println("Common logic");
        validateData();
    }
    
    private void validateData() {
        System.out.println("Validating...");
    }
    
    // 静态方法
    static void staticMethod1() {
        System.out.println("Static 1");
        commonStaticLogic();
    }
    
    static void staticMethod2() {
        System.out.println("Static 2");
        commonStaticLogic();
    }
    
    // 私有静态方法（Java 9+）
    private static void commonStaticLogic() {
        System.out.println("Common static logic");
    }
}

// 实现类
public class Implementation implements ModernInterface {
    @Override
    public void publicMethod() {
        System.out.println("Public method implementation");
    }
    
    public static void main(String[] args) {
        Implementation impl = new Implementation();
        impl.defaultMethod1();  // 可以调用默认方法
        // impl.commonLogic();  // 编译错误！私有方法不可见
        
        ModernInterface.staticMethod1();  // 可以调用静态方法
        // ModernInterface.commonStaticLogic();  // 编译错误！私有静态方法不可见
    }
}`
			}
		]
	}
];